/*
 * Remove Duplicates from Sorted Array II
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array A = [1,1,1,2,2,3],

Your function should return length = 5, and A is now [1,1,2,2,3].
 */
package com.xinpan.exercise;

public class RemoveDuplicateFromSortedArray2 {
    public int removeDuplicates(int[] A) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(A.length == 0)
            return 0;
        
        int i = 0;
        int j = 1;
        int cnt = 1;
        for(; j < A.length; j++)
        {
            if(A[j] == A[j-1])
            {
                if(cnt != 0)
                {
                    cnt--;
                    A[++i] = A[j];
                }
            }
            else
            {
                cnt = 1;
                A[++i] = A[j];
            }
        }
        return i+1;
    }
}
